import React from 'react'
import {connect,} from 'react-redux'
import {Link, withRouter,} from 'react-router-dom'
import {
    behaviorReq,
    followBasketballGameReq,
    getBasketballGameDetailReq,
    getBasketballGameFollowReq,
    getUserDetailReq
} from "../../apis/goApis";
import {GlobalStore} from "../../context";
import withDownload from "../../high-order-component/withDownload/withDownload";
import GameRoomHeader from "../game-room/components/Header/Header";
import {Icon} from "antd-mobile";
import moment from "moment";
import ShareIcon from "../../res/images/web/shared/share-icon.png";
import TeamAvatar from "../game-room/components/Header/Versus/TeamAvatar/TeamAvatar";
import ChatRoom from "../game-room/components/Main/chat-room/chat-room";
import LocalStorageService from "../../utils/LocalStorageService";
import liveBtnIcon from "../../res/images/web/game/game-video@2x.png";
import VideoPlayer from "../game-room/components/Header/VideoPlayer/VideoPlayer";
import {app_name} from "../../utils/constants";
import StarClickedIcon from "../../res/images/web/game-room/收藏点亮@2x.png";
import StarIcon from "../../res/images/web/game-room/like@2x.png";
import SharePopup from "../game-room/components/Header/SharePopup/SharePopup";
import GameRoomTab from "../game-room/components/Main/GameRoomTab/GameRoomTab";
import BasketballLive from "./basketball-live";
import BasketballStat from "./basketball-stat";
import {log} from "../../utils/commonfunc";

class BasketballGameRoomContainer extends React.Component {

    static contextType = GlobalStore

    constructor(props) {
        super(props)
        this.matchId = parseInt(this.props.match.params.gameId)
        this.uid = localStorage.getItem('userid')
        this.state = {
            downloadShow: true,
            connectWsOk: false,
            videoTag: false,
            player: null,
            marked: false,
            showSharePopup: false,
            tabs: [
                {title: '直播', active: true,},
                {title: '统计', active: false,},
                {title: '聊天', active: false,},
            ]
        }
        this.timerId = null
    }

    componentDidMount() {
        this.fetchUserDetail()
            .then(() => this.fetchGameDetail({id: this.matchId}))
            .then((resp) => {
                if (resp.data.ok) {
                    let game = resp.data.ok
                    if (game?.Zhibo?.length > 0) {
                        log('直播')
                        if (game.State !== '未开赛' && game.State !== '已完赛') {
                            log('gameon')
                            if (this.uid) {
                                return
                            } else {
                                this.props.history.push('../login')
                            }
                        }
                    }
                    this.setState({
                        connectWsOk: true,
                    })
                }
            })
            .then(() => this.getMarked())
            .then(() => this.setTitle())
            .then(() => this.freshGameDetail(this.matchId))
    }

    componentWillUnmount() {
        document.title = app_name
        this.props.setInitCurrentGame()
        this.clearFreshGameDetail()
    }

    setTitle() {
        const game = this.props.currentGame
        document.title = game.Zhuname + ' VS ' + game.Kename
    }

    freshGameDetail() {
        if (this.props.currentGame.State !== '已完赛') {
            this.timerId = setInterval(() => this.fetchGameDetail({id: this.matchId}), 60000)
        }
    }

    clearFreshGameDetail() {
        if (this.timerId) {
            clearInterval(this.timerId)
        }
    }

    getMarked = () => {
        if (this.uid) {
            getBasketballGameFollowReq({uid: this.uid,})
                .then(resp => {
                    const list = resp.data.ok
                    if (list && list.length > 0 && list.find(game => game.Id === this.matchId)) {
                        this.setState({
                            marked: true,
                        })
                    }
                })
        }
    }

    markGame = () => {
        if (LocalStorageService.get('isLogin')) {
            behaviorReq({
                userid: LocalStorageService.get('userid'),
                handle: '篮球关注',
            })
            const game = this.props.currentGame
            followBasketballGameReq({
                uid: this.uid,
                matchid: String(this.matchId),
                date: moment(game.Startt * 1000).format('YYYYMMDD'),
                del: this.state.marked,
            })
                .then((resp) => {
                    if (resp.data.ok) {
                        this.setState({
                            marked: !this.state.marked,
                        })
                    }
                })
        }

    }

    fetchUserDetail = () => {
        const login = LocalStorageService.get('isLogin')
        const uid = localStorage.getItem('userid')
        const flag = this.props.user.userdetail.initFlag
        if (login && flag === 0) {
            return this.props.fetchUserDetail({uid,})
        } else {
            return new Promise((resolve => resolve(true)))
        }
    }

    fetchGameDetail = (params) => {
        return this.props.doFetchBasketballGameDetail(params)
    }


    renderPlayer = (player) => {
        if (player) {
            return <div
                className='game-room-vs-player-container'
                style={{
                    width: '33%',
                    position: 'relative',
                }}
            >
                <TeamAvatar
                    iconUrl={player.logo}
                    atTop={true}
                    noPrefix
                />
                <div className='game-room-vs-player-name'>{player.name}</div>
            </div>
        }
    }

    goBack = () => {
        const ps = this.context.gamePagePosition.positions
        ps[0] = 1
        this.context.gamePagePosition.setPagePosition(ps)
        this.props.history.goBack()
    }

    destroyPlayer = () => {
        this.setState({
            videoTag: false,
        })
    }

    showShare = () => {
        this.setState({
            showSharePopup: true,
        })
    }

    hideSharePopup = () => {
        this.setState({
            showSharePopup: false,
        })
    }

    onTabClick = (e, i) => {
        this.setState({
            page: i,
        })
    }

    render() {

        const game = this.props.currentGame
        const downloadShow = this.props.downloadShow
        const videoSrc = game.Zhibo ? game.Zhibo[0][1] : ''
        const start = game.State !== '未开赛' && game.State !== '已完赛'
        const end = game.State === '已完赛'

        const vodBtn = <div
            className='game-room-header-icon-btn'
            onClick={() => {
                this.setState({
                    videoTag: true,
                })
            }}
        >
            <img alt='' src={liveBtnIcon} />
            <span>视频</span>
        </div>
        const FollowIconTemplate = (<img
            style={{
                height: '28px',
                width: '28px',
            }}
            src={this.state.marked ? StarClickedIcon : StarIcon}
            onClick={() => this.markGame()}
            alt=''
        />)
        const ShareIconTemplate = (<img
            onClick={() => this.showShare()}
            src={ShareIcon}
            alt=''
            style={{marginRight: '1rem',}}
        />)
        const homeScore = game.home ? game.home.score.reduce((a, b) => a + b, 0) : 0
        const awayScore = game.away ? game.away.score.reduce((a, b) => a + b, 0) : 0
        const header = this.state.videoTag
            ? null
            : <div className='game-room-header-container game-room-header-container-basketball'>

            <div className='game-room-header-title'>
                <Icon
                    type='left'
                    color='#fff'
                    size='lg'
                    onClick={() => this.goBack()}
                />

                <div className='game-room-header-title-category'>
                    <p>{game.Name}</p>
                    <p>{game.Startt && moment(game.Startt * 1000).format('YYYY年MM月DD日 HH:mm')}</p>
                </div>

                <div>
                    {ShareIconTemplate}
                    {end ? null : FollowIconTemplate}
                </div>
            </div>

            <div className='game-room-vs-container'>
                {this.renderPlayer(game.home ? game.home : {name: '', score: [], logo: '',})}
                <div
                    style={{
                        width: '33%',
                        textAlign: 'center',
                    }}
                >
                    <div className='game-room-vs-c-time' style={{color: '#fff',}}>{game.State}</div>
                    <div className='game-room-vs-score'>
                        {homeScore} - {awayScore}
                    </div>
                </div>
                {this.renderPlayer(game.away ? game.away : {name: '', score: [], logo: '',})}
            </div>

            <div
                className='flex-center-align-center'
                style={{
                    position: 'absolute',
                    bottom: '42px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    background: 'rgba(0,0,0,0.3)',
                }}
            >
                {start && videoSrc ? vodBtn : null}
            </div>
        </div>

        const player = this.state.videoTag ? <div
            style={{
                overflow: 'hidden',
                padding: 0,
                // position: 'fixed',
                // top: downloadShow ? 60 : 0,
                left: 0,
                zIndex: 999,
                height: 220,
                position: 'relative',
                width: window.innerWidth,
            }}
        >
            <Icon
                type='left'
                color='#fff'
                size='lg'
                style={{
                    position: 'absolute',
                    left: '10px',
                    top: '10px',
                    zIndex: 999,
                }}
                onClick={this.destroyPlayer}
            />
            <VideoPlayer
                videoSrc={game.Zhibo ? game.Zhibo[0][1] : ''}
                destroyPlayer={this.destroyPlayer}
            />
        </div> : null

        return <>
            {this.props.renderDownloadHint({level: 2,})}
            {header}
            {player}
            <SharePopup
                showSharePopup={this.state.showSharePopup}
                hideSharePopup={this.hideSharePopup}
                history={this.props.history}
            />
            <div
                style={{
                    overflowY: 'scroll',
                }}
                className={downloadShow ? 'game-room-main-container-d' : 'game-room-main-container'}
            >
                <GameRoomTab
                    tabs={this.state.tabs}
                    prerenderingSiblingsNumber={0}
                    animated={false}
                    // destroyInactiveTab={true}
                    // initialPage={initialPage}
                    // initialPage={4}
                    tabBarUnderlineStyle={{background: '#36C8B9',}}
                    onTabClick={(e, i) => this.onTabClick(e, i)}
                    onChange={(e, i) => this.onTabClick(e, i)}
                    page={this.state.page}
                >
                    <BasketballLive />
                    <BasketballStat />
                    <ChatRoom
                        type='game'
                        giftNotice
                        goalNotice
                        // holdon={true}
                        connectWsOk={this.state.connectWsOk}
                        chatFlag={1}
                    />
                </GameRoomTab>

            </div>

        </>
    }
}

const mapState = state => ({
    user: state.user,
    game: state.game,
    games: state.game.games,
    currentGame: state.game.currentGame,
})

const mapDispatch = dispatch => ({
    fetchUserDetail:(payload) => dispatch.user.fetchUserDetail(payload),
    doWechatPay: (payload) => dispatch.user.doWechatPay(payload),
    doCheckWechatOrder: (payload) => dispatch.user.doCheckWechatOrder(payload),
    doFetchBasketballGameDetail: (payload) => dispatch.game.doFetchBasketballGameDetail(payload),
    setInitCurrentGame: () => dispatch.game.setInitCurrentGame(),
})

export default connect(mapState, mapDispatch)(withRouter(withDownload(BasketballGameRoomContainer)))